$(function () {
    var pic = [];
    var pic2 = [];
    var layer;
    var table;
    var form;
    var upload;
    var contentIndex;
    var categoryId;
    var layedit;
    var setting = {
        async: {
            enable: true,
            url: "/content/showContentCategory",
            autoParam: ["id"],
            dataFilter: filter,

        },
        callback: {
            onClick: zTreeOnClick
        }
    };

    function zTreeOnClick(event, treeId, treeNode) {
        categoryId = treeNode.id;
        if (treeNode.isParent) {
            return;
        }
        //不为true
        $.ajax({
            type: "POST",
            url: "/content/findContentByCId",
            dataType: "json",
            data: "categoryId=" + treeNode.id,
            success: function (res) {
                if (res.count == 0) {
                    layer.alert(res.msg);
                    return;
                }

                table.reload('contentTable', {
                    url: '/content/showContent',
                    where: {
                        categoryId: treeNode.id
                    }
                });
            }
        });
    };

    function filter(treeId, parentNode, childNodes) {
        if (!childNodes) return null;
        for (var i = 0, l = childNodes.length; i < l; i++) {
            childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
        }
        return childNodes;
    }

    //初始化树形结构
    $.fn.zTree.init($("#contentCategoryTree"), setting);
    //layui初始化
    layui.use(['table', 'form', 'upload'], function () {
        form = layui.form,
            upload = layui.upload,
            layer = layui.layer,
            table = layui.table;


        //只要用户点击上传图片按钮以后 选择了图片以后 就会执行这个代码 pic
        upload.render({
            elem: '#uploadPic'
            , url: '/content/addPic' //改成您自己的上传接口
            , multiple: true
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    //往showPic（div）里面创建img标签设置他的一系列东西
                    $('#pic').append('<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img">')
                });
            }
            , done: function (res) {
                console.log(res.data.src)
                pic.push(res.data.src);
            }
        });
        //pic2
        upload.render({
            elem: '#uploadPic2'
            , url: '/content/addPic' //改成您自己的上传接口
            , multiple: true
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    //往showPic（div）里面创建img标签设置他的一系列东西
                    $('#pic2').append('<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img">')
                });
            }
            , done: function (res) {
                pic2.push(res.data.src);
            }
        });


        table.render({
            elem: '#contentTable'
            , url: '/content/showContent'
            , toolbar: '#contentBtn' //开启头部工具栏，并为其绑定左侧模板
            , defaultToolbar: ['filter', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]
            , title: '内容表'
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', title: 'ID', width: 80, fixed: 'left', unresize: true, sort: true}
                , {field: 'title', title: '标题', width: 80, edit: 'text'}
                , {field: 'subTitle', title: '子标题', width: 100, edit: 'text', sort: true}
                , {field: 'titleDesc', title: '描述', width: 80}
                , {field: 'url', title: '链接', width: 80}
                , {field: 'pic', title: '图片1', width: 80, sort: true, templet: '#contentImage1'}
                , {field: 'pic2', title: '图片2', width: 80, templet: '#contentImage2'}
                , {field: 'content', title: '内容', width: 80, sort: true}
                , {
                    field: 'created',
                    title: '创建时间',
                    width: 100,
                    templet: "<div>{{layui.util.toDateString(d.created, 'yyyy-MM-dd HH:mm:ss')}}</div>"
                }
                , {
                    field: 'updated',
                    title: '更新时间',
                    width: 100,
                    templet: "<div>{{layui.util.toDateString(d.updated, 'yyyy-MM-dd HH:mm:ss')}}</div>"
                }
            ]]
            , page: true
        });
        //头工具栏事件
        table.on('toolbar(content)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'deleteContent':
                    var data = checkStatus.data;
                    $.ajax({
                        type: "POST",
                        url: "/content/delContent",
                        dataType: "json",
                        contentType: 'application/json;charset=UTF-8',
                        data: JSON.stringify(data),
                        success: function (res) {
                            layer.alert(res.msg);
                            table.reload('contentTable', {
                                url: '/content/showContent',
                                where: {
                                    categoryId: res.data
                                }
                            });
                        }
                    });
                    break;
                case 'addContent':
                    layer.open({
                        type: 1,
                        title: '内容添加',
                        offset: 't',
                        skin: 'layui-layer-lan', //加上边框
                        area: ['80%', '80%'], //宽高
                        content: $('#addContent'),
                        btn: ['确定', '取消'],
                        yes: function (index, layero) {

                            var json = {};
                            json.categoryId = categoryId;
                            json.title = $("#title").val();
                            json.subTitle = $("#subTitle").val();
                            json.url = $("#url").val();
                            json.content = layedit.getContent(contentIndex);
                            json.pic = pic.join(",");
                            json.pic2 = pic2.join(",");
                            console.log(json);
                            $.ajax({
                                type: "POST",
                                url: "/content/addContent",
                                dataType: "json",
                                contentType: 'application/json;charset=UTF-8',
                                data: JSON.stringify(json),
                                success: function (res) {
                                    if (res.code == "ErrorResponse") {
                                        window.location.href = "http://localhost:8080/error.jsp";
                                    } else {
                                        layer.alert(res.msg);
                                    }

                                    //使用layui情况form表单input输入框的值
                                    $("#addContentForm")[0].reset();
                                    layui.form.render();
                                    //自己情况 多图片上传的图片
                                    $("#pic>img").remove();
                                    $("#pic2>img").remove();
                                    contentIndex = layedit.build('content');
                                    //刷新页面
                                    table.reload('contentTable', {
                                        url: '/content/showContent',
                                        where: {
                                            categoryId: categoryId
                                        }
                                    });

                                }
                            });

                        }

                    })
                    layui.use('layedit', function () {
                        layedit = layui.layedit;
                        //cms内容富文本编辑框上传图片的地址
                        layedit.set({
                            uploadImage: {
                                url: '/content/addPic' //接口url
                                , type: 'post' //默认post
                            }
                        });
                        //构建一个默认的编辑器
                        contentIndex = layedit.build('content');
                        //from表单提交数据 是以name = des value = 用户输入的值
                        layedit.sync(contentIndex);
                        //编辑器外部操作
                        var active = {
                            content: function () {
                                alert(layedit.getContent(contentIndex)); //获取编辑器内容
                            }
                            , text: function () {
                                alert(layedit.getText(contentIndex)); //获取编辑器纯文本内容
                            }
                            , selection: function () {
                                alert(layedit.getSelection(contentIndex));
                            }
                        };
                    });
                    break;
                case 'updateContent':
                    layer.msg(checkStatus.isAll ? '全选' : '未全选');
                    break;
            }
            ;
        });

    });

})